<template>
  <div class="monitor-dashboard">
    <el-row :gutter="20">
      <!-- 概览数据 -->
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header">
            <span>销售概览</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="refreshData">刷新</el-button>
          </div>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="data-item">
                <div class="data-title">今日销售额</div>
                <div class="data-value">¥{{ overview.todaySales.toFixed(2) }}</div>
                <div class="data-compare" :class="{'up': overview.todaySales > overview.yesterdaySales}">
                  {{ ((overview.todaySales - overview.yesterdaySales) / overview.yesterdaySales * 100).toFixed(1) }}%
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="data-item">
                <div class="data-title">今日订单数</div>
                <div class="data-value">{{ overview.todayOrders }}</div>
                <div class="data-compare" :class="{'up': overview.todayOrders > overview.yesterdayOrders}">
                  {{ ((overview.todayOrders - overview.yesterdayOrders) / overview.yesterdayOrders * 100).toFixed(1) }}%
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="data-item">
                <div class="data-title">今日会员数</div>
                <div class="data-value">{{ overview.todayMembers }}</div>
                <div class="data-compare" :class="{'up': overview.todayMembers > overview.yesterdayMembers}">
                  {{ ((overview.todayMembers - overview.yesterdayMembers) / overview.yesterdayMembers * 100).toFixed(1) }}%
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="data-item">
                <div class="data-title">转化率</div>
                <div class="data-value">{{ overview.conversion }}%</div>
                <div class="data-compare" :class="{'up': overview.conversion > overview.yesterdayConversion}">
                  {{ (overview.conversion - overview.yesterdayConversion).toFixed(1) }}%
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 销售趋势图 -->
      <el-col :span="16">
        <el-card class="box-card">
          <div slot="header">
            <span>销售趋势</span>
            <el-radio-group v-model="trendPeriod" size="small" style="float: right">
              <el-radio-button label="week">周</el-radio-button>
              <el-radio-button label="month">月</el-radio-button>
              <el-radio-button label="quarter">季</el-radio-button>
            </el-radio-group>
          </div>
          <div class="chart-container">
            <v-chart :options="salesTrendChart" autoresize />
          </div>
        </el-card>
      </el-col>

      <!-- 热销商品排行 -->
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header">
            <span>热销商品排行</span>
            <el-select v-model="topProductsPeriod" size="small" style="float: right; width: 100px">
              <el-option label="今日" value="today" />
              <el-option label="本周" value="week" />
              <el-option label="本月" value="month" />
              <el-option label="本季" value="quarter" />
            </el-select>
          </div>
          <el-table :data="topProducts" style="width: 100%" size="small">
            <el-table-column prop="product_name" label="商品名称" />
            <el-table-column prop="sales_quantity" label="销量" width="80" />
            <el-table-column prop="sales_amount" label="销售额" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.sales_amount.toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 性能监控 -->
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header">
            <span>性能监控</span>
          </div>
          <div class="performance-metrics">
            <div class="metric-item">
              <span class="label">页面加载时间</span>
              <span class="value">{{ pageLoadTime }}ms</span>
            </div>
            <div class="metric-item">
              <span class="label">首次内容绘制</span>
              <span class="value">{{ firstPaintTime }}ms</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- API监控 -->
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header">
            <span>API监控</span>
          </div>
          <div class="api-metrics">
            <el-table :data="apiMetrics" style="width: 100%" size="small">
              <el-table-column prop="url" label="接口" />
              <el-table-column prop="responseTime" label="响应时间(ms)" width="120" />
            </el-table>
          </div>
        </el-card>
      </el-col>

      <!-- 错误监控 -->
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header">
            <span>错误监控</span>
          </div>
          <div class="error-metrics">
            <el-table :data="errorLogs" style="width: 100%" size="small">
              <el-table-column prop="type" label="类型" width="100" />
              <el-table-column prop="message" label="错误信息" />
              <el-table-column prop="time" label="时间" width="180" />
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { performanceMonitor } from '@/utils/monitor'
import VChart from 'vue-echarts'
import 'echarts/lib/chart/line'
import 'echarts/lib/chart/bar'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/title'
import 'echarts/lib/component/legend'
import 'echarts/lib/component/grid'
import {
  getOverview,
  getSalesTrend,
  getSalesComposition,
  getSalespersonRank,
  getComprehensiveStats,
  getSalesCurve,
  getTopProducts
} from '@/api/dashboard'

export default {
  name: 'MonitorDashboard',
  
  components: {
    VChart
  },
  
  data() {
    return {
      // 概览数据
      overview: {
        todaySales: 0,
        yesterdaySales: 0,
        todayOrders: 0,
        yesterdayOrders: 0,
        todayMembers: 0,
        yesterdayMembers: 0,
        conversion: 0,
        yesterdayConversion: 0
      },
      
      // 销售趋势
      trendPeriod: 'week',
      salesTrend: {
        dates: [],
        sales: [],
        orders: []
      },
      
      // 热销商品
      topProductsPeriod: 'today',
      topProducts: [],
      
      // 性能指标
      pageLoadTime: 0,
      firstPaintTime: 0,
      
      // 销售构成
      salesComposition: [],
      
      // 销售员排行
      salespersonRank: [],
      
      // 综合统计
      comprehensiveStats: {
        total_products: 0,
        total_customers: 0,
        total_orders: 0
      },
      
      // 销售曲线
      salesCurve: [],
      apiMetrics: [],
      errorLogs: []
    }
  },
  
  computed: {
    salesTrendChart() {
      return {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['销售额', '订单数']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.salesTrend.dates
        },
        yAxis: [
          {
            type: 'value',
            name: '销售额',
            axisLabel: {
              formatter: '¥{value}'
            }
          },
          {
            type: 'value',
            name: '订单数',
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: '销售额',
            type: 'line',
            data: this.salesTrend.sales
          },
          {
            name: '订单数',
            type: 'bar',
            yAxisIndex: 1,
            data: this.salesTrend.orders
          }
        ]
      }
    }
  },
  
  watch: {
    trendPeriod() {
      this.fetchData()
    },
    topProductsPeriod() {
      this.fetchData()
    }
  },
  
  mounted() {
    this.initializeMetrics()
    this.fetchData()
  },
  onLoad() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      try {
        // 获取概览数据
        const overviewRes = await getOverview()
        this.overview = overviewRes.data
        
        // 获取销售趋势
        const trendRes = await getSalesTrend(
          this.trendPeriod === 'week' ? 7 : 14,
          this.trendPeriod === 'month' ? 30 : 90
        )
        this.salesTrend = trendRes.data
        
        // 获取热销商品
        const topProductsRes = await getTopProducts(this.topProductsPeriod, 10)
        this.topProducts = topProductsRes.data

        // 获取销售构成
        const compositionRes = await getSalesComposition()
        this.salesComposition = compositionRes.data

        // 获取销售员排行
        const salespersonRes = await getSalespersonRank(10)
        this.salespersonRank = salespersonRes.data

        // 获取综合统计
        const comprehensiveRes = await getComprehensiveStats()
        this.comprehensiveStats = comprehensiveRes.data

        // 获取销售曲线
        const curveRes = await getSalesCurve(this.trendPeriod, 'day')
        this.salesCurve = curveRes.data

      } catch (error) {
        console.error('获取数据失败：', error)
        this.$message.error(error.response?.data?.detail || '获取数据失败')
      }
    },
    
    refreshData() {
      this.fetchData()
    },
    
    initializeMetrics() {
      // 获取性能指标
      this.pageLoadTime = performanceMonitor.pageLoadTime()
      this.firstPaintTime = performanceMonitor.firstPaintTime()
      
      // 初始化其他数据
      this.salesComposition = []
      this.salespersonRank = []
      this.comprehensiveStats = {
        total_products: 0,
        total_customers: 0,
        total_orders: 0
      }
      this.salesCurve = []
    }
  }
}
</script>

<style lang="scss" scoped>
.monitor-dashboard {
  padding: 20px;
  
  .box-card {
    margin-bottom: 20px;
  }
  
  .data-item {
    text-align: center;
    padding: 20px;
    
    .data-title {
      font-size: 14px;
      color: #909399;
      margin-bottom: 10px;
    }
    
    .data-value {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 10px;
    }
    
    .data-compare {
      font-size: 12px;
      color: #F56C6C;
      
      &.up {
        color: #67C23A;
      }
    }
  }
  
  .chart-container {
    height: 400px;
  }
  
  .performance-metrics {
    .metric-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 15px;
      
      .label {
        color: #606266;
      }
      
      .value {
        font-weight: bold;
        color: #409EFF;
      }
    }
  }
}
</style> 